package progress.exa28_2.part2;

import java.util.concurrent.*;

public class PriorityBlockingQueueStudy {

    private static final BlockingQueue<Integer> buffer = new PriorityBlockingQueue<>(10);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(new ProducerTask());
        Thread.sleep(5000);
        executorService.execute(new ConsumerTask());
        executorService.shutdown();
    }


    /**
     * 生产者任务
     */
    private static class ProducerTask implements Runnable{
        public void run() {
            try{
                int i=100;
                while(true){
                    System.out.println("Producer writes"+i);
                    //如果队列满了进入阻塞
                    buffer.put(i--);
                    //线程休眠
                    Thread.sleep((int)(Math.random()*1000));
                }
            }catch (InterruptedException ex){
                ex.printStackTrace();
            }
        }
    }


    /**
     * 消费者任务
     */
    private static class ConsumerTask implements Runnable{
        public void run() {
            try {
                while (true) {
                    //从队列中读取元素，如果队列空了，进入阻塞
                    System.out.println("\t\t\tConsumer reads"+buffer.take());
                    //线程休眠
                    Thread.sleep((int)(Math.random()*1000));
                }
            }catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}
